package com.hiof.overlays;

import com.hiof.Configuration;
import com.hiof.R;
import com.hiof.servercommunication.receive.beans.GeoPoint;
import com.hiof.settings.user.UserConfiguration;
import com.hiof.utility.Utility;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: manish
 * Date: 4/17/12
 * Time: 10:18 PM
 * To change this template use File | Settings | File Templates.
 */
public class MapPointsManager {
    //singleton here
    private static MapPointsManager instance;
    public ArrayList<GeoPoint> mapPoints = new ArrayList<GeoPoint>();

    public static MapPointsManager getInstane() {
        if (null == instance) {
            instance = new MapPointsManager();
        }
        return instance;
    }

    public GeoPoint getPoint(int index) {
        if (mapPoints.size() > 0) {
            if (index >= mapPoints.size())
                return mapPoints.get(mapPoints.size() - 1);
            else if (index < 0)
                return mapPoints.get(0);
            else
                return mapPoints.get(index);
        } else {
            parseMap(UserConfiguration.getInstance().getRouteId());
            return new GeoPoint();
        }
    }

    public com.google.android.maps.GeoPoint getGoogleGeoPoint(int index) {
        return getPoint(index).getGoogleGeoPoint();
    }

    public int getRouteMapSize() {
        return mapPoints.size();
    }

    public void parseMap(int routeId) {
        int mapFile = R.raw.testroute1;
        if (routeId == 1) {
            mapFile = R.raw.testroute1;
        } else if (routeId == 2) {
            mapFile = R.raw.testroute1;
        } else if(routeId ==3){
            mapFile = R.raw.treninsgrunde;
        }
        InputStream inputStream = Configuration.getInstance().getCurrentContext().getResources().openRawResource(mapFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                inputStream));
        String strLine;
        String[] lineSplit = new String[3];
        try {
            while (br.ready()) {
                strLine = br.readLine();
                lineSplit = strLine.split(",");
                double lon = Double.parseDouble(lineSplit[0].trim());
                double lat = Double.parseDouble(lineSplit[1].trim());
                double height = (Double.parseDouble(lineSplit[2].trim()));
                mapPoints.add(new GeoPoint(lat, lon, height));

            }
            inputStream.close();
            br.close();
        } catch (Exception e) {
            Utility.error(this.getClass().toString(), "Exception in parseMap():" + String.valueOf(e.getMessage()));
        }
    }

    public void destroy() {
        if (mapPoints != null)
            mapPoints.clear();
    }
}
